package indi.luckly.service.impl;

import indi.luckly.common.ApiException;
import indi.luckly.common.key.ErrorKey;
import indi.luckly.common.request.UpDateUserInfoParams;
import indi.luckly.common.response.QueryUserBaseInfoResponseData;
import indi.luckly.common.response.ResponseResult;
import indi.luckly.entity.UserEntity;
import indi.luckly.entity.UserInfoEntity;
import indi.luckly.mapper.IUserInfoMapper;
import indi.luckly.mapper.IUserMapper;
import indi.luckly.service.IUserService;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(value = "UserService")
public class UserServiceImpl implements IUserService {
    @Autowired
    @Qualifier("UserInfoMapper")
    private IUserInfoMapper mUserInfoMapper;
    @Autowired
    @Qualifier("UserMapper")
    private IUserMapper mUserMapper;

    @Override
    public QueryUserBaseInfoResponseData queryUserInfo(String userNumber) throws ApiException, InvocationTargetException, IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        map.put("user_number", userNumber);
        final List<UserInfoEntity> userInfoEntities = mUserInfoMapper.selectByMap(map);
        QueryUserBaseInfoResponseData data = new QueryUserBaseInfoResponseData();
        if (userInfoEntities != null && userInfoEntities.size() > 0) {
            final UserInfoEntity userEntity = userInfoEntities.get(0);
            BeanUtils.copyProperties(data,userEntity);
            return data;
        } else {
            final List<UserEntity> userEntities = mUserMapper.selectByMap(map);
            if (userEntities == null || userEntities.size() == 0) {
                throw ApiException.create(ErrorKey.USER_NON_EXISTENT);
            } else {
                throw ApiException.create(ErrorKey.USER_INFO_NON_EXISTENT);
            }

        }
    }
    @Override
    public void upDateUserInfo(UpDateUserInfoParams params) throws ApiException, InvocationTargetException, IllegalAccessException {

        if (params == null) {//参数缺失
            throw ApiException.create(ErrorKey.PARAMS_DELETION);
        }
        UserInfoEntity userEntity = new UserInfoEntity();
        BeanUtils.copyProperties(userEntity,params);

        int i = mUserInfoMapper.upDateUserInfo(userEntity);

        if (i <= 0) {
            int insertRet = mUserInfoMapper.insert(userEntity);
            if (insertRet <= 0) {
                throw ApiException.create(ErrorKey.UPDATE_USER_INFO_ERROR);
            }
        } else {
            throw ApiException.create(ErrorKey.UPDATE_USER_INFO_ERROR);
        }

    }
}
